from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
from datetime import datetime
import copy
import time
from functools import wraps

# Pydantic模型定义
class CardResponse(BaseModel):
    id: int
    title: str
    description: str
    image: str
    location: str
    category: str
    type: Optional[str] = None
    views: int
    height: str

class DemoResponse(BaseModel):
    message: str
    features: List[str]
    example_data: Dict[str, Any]

# 装饰器：性能监控
def performance_monitor(func):
    """装饰器：监控函数执行时间"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"函数 {func.__name__} 执行时间: {end_time - start_time:.4f} 秒")
        return result
    return wrapper

# 工具类：数据处理
class DataProcessor:
    """数据处理工具类"""

    @staticmethod
    def create_sample_cards() -> List[Dict[str, Any]]:
        """静态方法：创建示例卡片数据"""
        return [
            {
                "id": 1,
                "type": "路线",
                "image": "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=400&h=200&fit=crop",
                "views": 813,
                "location": "苏州市",
                "title": "网师园|沧浪亭十全街漫游",
                "description": "网师园夜游偷师昆曲腔,沧浪亭漏窗框住宋朝光影 🌙",
                "category": "热门",
                "height": "short"
            },
            {
                "id": 2,
                "type": "景点",
                "image": "https://images.unsplash.com/photo-1540959733332-eab4deabeeaf?w=400&h=300&fit=crop",
                "views": 78,
                "location": "日本",
                "title": "长野新泫周游券深度游",
                "description": "玩转长野新泫:泡猴汤、访古寺、尝地酒五日巡礼 🚄",
                "category": "境外",
                "height": "tall"
            },
            {
                "id": 3,
                "image": "https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=400&h=250&fit=crop",
                "views": 104,
                "location": "荆州市",
                "title": "神农架秘境导览",
                "description": "华中屋脊·土家原乡·高山湿地·神农祭祀 🌲",
                "category": "景区",
                "height": "medium"
            }
        ]

    @staticmethod
    def process_with_generator(cards_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """生成器：逐个处理卡片数据"""
        for card in cards_data:
            # 深拷贝以避免修改原数据
            processed_card = copy.deepcopy(card)
            # 添加处理时间戳
            processed_card["processed_at"] = datetime.now().isoformat()
            yield processed_card

    @staticmethod
    def filter_by_category(cards_data: List[Dict[str, Any]], category: str) -> List[Dict[str, Any]]:
        """迭代器：按分类过滤卡片"""
        return [card for card in cards_data if card.get("category") == category]

    @classmethod
    def get_hot_cards(cls) -> List[Dict[str, Any]]:
        """类方法：获取热门卡片"""
        all_cards = cls.create_sample_cards()
        return cls.filter_by_category(all_cards, "热门")

# 创建路由器
api_router = APIRouter()

# 简单的API端点
@api_router.get("/cards")
@performance_monitor
def get_cards():
    """获取卡片列表 - 演示Python高级特性"""

    print("🔄 开始处理卡片数据...")

    # 创建示例数据
    all_cards = DataProcessor.create_sample_cards()
    print(f"✅ 创建了 {len(all_cards)} 个卡片")

    # 使用生成器处理数据
    processed_cards = list(DataProcessor.process_with_generator(all_cards))
    print(f"✅ 生成器处理了 {len(processed_cards)} 个卡片")

    # 使用迭代器过滤热门卡片
    hot_cards = DataProcessor.filter_by_category(processed_cards, "热门")
    print(f"✅ 迭代器过滤出 {len(hot_cards)} 个热门卡片")

    # 转换为响应格式
    card_responses = []
    for card in processed_cards[:3]:  # 只返回前3个
        card_response = CardResponse(
            id=card["id"],
            title=card["title"],
            description=card["description"],
            image=card["image"],
            location=card["location"],
            category=card["category"],
            type=card.get("type"),
            views=card["views"],
            height=card["height"]
        )
        card_responses.append(card_response)

    return {
        "message": "Python高级特性演示API",
        "cards": card_responses,
        "total": len(all_cards),
        "features_used": [
            "🧪 生成器(Generator) - 内存友好的数据处理",
            "🔄 迭代器(Iterator) - 惰性求值的数据遍历",
            "📋 深浅拷贝 - 数据保护和性能优化",
            "🔧 静态方法(Static Methods) - 工具类方法",
            "🎨 装饰器(Decorator) - 功能增强"
        ]
    }

@api_router.get("/demo")
def demo_features():
    """Python高级特性演示"""

    print("🎯 演示Python高级特性...")

    # 演示深浅拷贝
    original_data = {"id": 1, "data": {"value": 100}}
    shallow_copy = copy.copy(original_data)
    deep_copy = copy.deepcopy(original_data)

    shallow_copy["data"]["value"] = 200  # 影响原始数据
    deep_copy["data"]["value"] = 300    # 不影响原始数据

    # 演示静态方法和类方法
    sample_cards = DataProcessor.create_sample_cards()
    hot_cards = DataProcessor.get_hot_cards()

    return {
        "message": "Python高级特性演示",
        "generator_demo": "使用生成器逐个处理数据",
        "iterator_demo": "使用迭代器过滤数据",
        "copy_demo": {
            "original_after_shallow": original_data["data"]["value"],  # 200 (受影响)
            "shallow_copy": shallow_copy["data"]["value"],             # 200
            "deep_copy": deep_copy["data"]["value"]                    # 300
        },
        "static_methods": "使用静态方法创建和管理数据",
        "class_methods": "使用类方法获取热门卡片",
        "decorators": "使用装饰器增强功能",
        "total_sample_cards": len(sample_cards),
        "hot_cards_count": len(hot_cards)
    }

@api_router.get("/features")
def show_features():
    """展示Python高级特性"""

    print("📋 展示Python 5大高级特性...")

    # 演示静态方法
    sample_cards = DataProcessor.create_sample_cards()
    hot_cards = DataProcessor.get_hot_cards()

    # 演示深浅拷贝
    original_data = {"metadata": {"views": 100}}
    shallow_copy = copy.copy(original_data)
    deep_copy = copy.deepcopy(original_data)

    shallow_copy["metadata"]["views"] = 200  # 影响原始数据
    deep_copy["metadata"]["views"] = 300    # 不影响原始数据

    return {
        "message": "Python 5大高级特性展示",
        "features": [
            "🧪 生成器 (Generator) - 内存友好的数据处理",
            "🔄 迭代器 (Iterator) - 惰性求值的数据遍历",
            "🎨 装饰器 (Decorator) - 功能增强和代码复用",
            "📋 深浅拷贝 - 数据保护和性能优化",
            "🔧 静态方法 (Static Methods) - 工具类方法设计"
        ],
        "copy_demonstration": {
            "original_after_shallow": original_data["metadata"]["views"],  # 200
            "shallow_copy": shallow_copy["metadata"]["views"],            # 200
            "deep_copy": deep_copy["metadata"]["views"]                   # 300
        },
        "total_sample_cards": len(sample_cards),
        "hot_cards_count": len(hot_cards),
        "example_cards": sample_cards[:2]
    }

# 将API路由添加到主应用
def include_api_routes(app):
    """包含API路由到主应用"""
    app.include_router(api_router, prefix="/api/v1", tags=["卡片API"])
    return app
